﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using Circle.Domain.Entity;
using Microsoft.Practices.Unity;
using Circle.Domain.Interface.Service;
using Circle.Domain.Model;

namespace Circle.Service
{
    public abstract class BaseOwnerCrudService<T> : BaseCrudService<T> where T : BaseOwnerEntity, new()
    {
        [Dependency]
        public IMemberUserService MemberUserService { get; set; }

        [Dependency]
        public IPermissionService PermissionService { get; set; }

        public override T Create()
        {
            //Create should be always available,
            //The userid should not be set until added to db
            //if (!Security.IsCurrentUserValid) { throw new InvalidOperationException("Current user must be valid for create operation"); }
            T item = base.Create();
            if (Security.CurrentUser != null) 
            {
                item.UserId = Security.CurrentUser.UserId;
                item.UserName = Security.CurrentUser.UserName;
            }
            //item.UserId = x.UserId = Security.CurrentUser.UserId;
            return item;
        }


        public override IQueryable<T> All
        {
            get
            {
                return Repository.All.Include(x => x.User);
            }
        }

        //public override T Get(Guid id, string includeSelector = null)
        //{
        //    var query = AddIncludeSelector(All, includeSelector);
        //    return query.Include(x => x.User).Where(x => x.Id == id).SingleOrDefault();
        //}

        protected override OperationStatus Add(T item)
        {
            item.User = MemberUserService.Get(item.UserId);
            return base.Add(item);
        }
    }
}
